package cn.com.cym.gamezao.service.recruit.impl;

import cn.com.cym.gamezao.base.ResultResponse;
import cn.com.cym.gamezao.entity.authorize.User;
import cn.com.cym.gamezao.entity.xmu.recruit.WorkExperience;
import cn.com.cym.gamezao.exception.BaseException;
import cn.com.cym.gamezao.jwt.RequestUser;
import cn.com.cym.gamezao.repository.xmu.recruit.WorkExperienceRepository;
import cn.com.cym.gamezao.service.recruit.WorkExperienceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class WorkExperienceImpl implements WorkExperienceService {

    final WorkExperienceRepository workExperienceRepository;

    WorkExperienceImpl(WorkExperienceRepository workExperienceRepository){
        this.workExperienceRepository = workExperienceRepository;
    }

    @Override
    public List<WorkExperience> searchByCurrentUser() {
        final User user = RequestUser.get();
        if(user.getUserType() == null){
            throw new BaseException("没有获取权限",new ResultResponse("没有获取权限",403));
        }
        return this.workExperienceRepository.findAllByUser(user);
    }

    @Override
    public List<WorkExperience> searchByCurrentUserId(Long userId) {
        return this.workExperienceRepository.findAllByUserId(userId);
    }

    @Override
    public int save(WorkExperience trainExperience) {
        final User user = RequestUser.get();
        trainExperience.setUser(user);
        this.workExperienceRepository.save(trainExperience);
        // 执行缓存刷新，避免线程数据获取失败
        this.workExperienceRepository.flush();
        return 1;
    }

    @Override
    public int update(WorkExperience workExperience, Long id) {
        final User user = RequestUser.get();
        WorkExperience byId = this.workExperienceRepository.findById(id).get();
        if(!byId.getUser().getUserName().equals(user.getUserName())){
            throw new BaseException("没有修改他人信息权限",new ResultResponse("没有修改他人信息权限",401));
        }
        // 复制
        workExperience.setUser(user).setId(id);
        BeanUtils.copyProperties(workExperience,byId);
        this.workExperienceRepository.save(byId);
        return 1;
    }

    @Override
    public void deleteById(Long id) {
        this.workExperienceRepository.deleteById(id);
    }

    @Override
    public List<WorkExperience> findAllByUser(User user) {
        return this.workExperienceRepository.findAllByUser(user);
    }
}
